package com.github.permissiondog.cancanpbackend.service;

import com.github.permissiondog.cancanpbackend.Database;
import com.github.permissiondog.cancanpbackend.dao.ResourceDao;
import com.github.permissiondog.cancanpbackend.model.Resource;
import com.github.permissiondog.cancanpbackend.util.Hash;
import lombok.Getter;
import org.apache.ibatis.session.SqlSession;

public class ResourceService {
    private ResourceService() {

    }

    @Getter
    private static final ResourceService instance = new ResourceService();

    public String createResource(byte[] data, String type) {
        var r = new Resource();
        r.setData(data);
        r.setSha(Hash.sha512(data));
        r.setType(type);
        try (SqlSession session = Database.getInstance().openSession()) {
            ResourceDao resourceDao = session.getMapper(ResourceDao.class);
            resourceDao.insertResource(r);
            return r.getSha();
        }
    }

    public Resource getResource(String sha) {
        try (SqlSession session = Database.getInstance().openSession()) {
            ResourceDao resourceDao = session.getMapper(ResourceDao.class);
            return resourceDao.getResource(sha);
        }
    }

    public void deleteResource(String sha) {
        try (SqlSession session = Database.getInstance().openSession()) {
            ResourceDao resourceDao = session.getMapper(ResourceDao.class);
            resourceDao.deleteResource(sha);
        }
    }
}
